﻿using FineUI;
using SysManage.BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core;
using ZHDJ.Data;
using ZHDJ.Data.Models.Org;

namespace SysManage.Module.Org
{
    public partial class PartyOrgMemberImport : PageBase
    {
        private object MemberSession
        {
            get
            {
                return this.ViewState["_IMPORT_PARTY_MEMBER_"];
            }
            set
            {
                if (this.ViewState["_IMPORT_PARTY_MEMBER_"] != null)
                    this.ViewState["_IMPORT_PARTY_MEMBER_"] = value;
                else
                    this.ViewState.Add("_IMPORT_PARTY_MEMBER_", value);
            }
        }

        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        #region 数据加载
        private void LoadData()
        {
            // 权限检查
            //CheckPowerWithButton("PartyArticleAdd", btnAdd);

            //btnAdd.OnClientClick = Dialog.GetShowReference("PartyDonationEdit.aspx?category=" + category, "编辑");
            // 每页记录数
            //Grid1.PageSize = ConfigHelper.PageSize;

            BindGrid();
        }

        private void BindGrid()
        {
            //var ds = PartyATMSaveAndTake.GetGridData(Grid1.PageIndex, Grid1.PageSize, this.txtName.Text, this.CurrentUser.LoginID, this.ppBranch.Value, this.ddlTitular.SelectedValue, this.ddlThingType.SelectedValue, this.ddlPurposes.SelectedValue, this.ddlSaveModus.SelectedValue, this.ddlState.SelectedValue, this.txtCreateBy.Text);

            //grid.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            //grid.DataSource = ds.Tables[0];
            //grid.DataBind();
        }

        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            //CheckPowerWithWindowField("PartyArticleEdit", Grid1, "editField");
            //CheckPowerWithLinkButtonField("PartyArticleDelete", Grid1, "deleteField");
        }

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            grid.SortDirection = e.SortDirection;
            grid.SortField = e.SortField;
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string PartyArticleId = GetSelectedDataKeyID(grid);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                //if (!CheckPower("PartyArticleDelete"))
                //{
                //    CheckPowerFailWithAlert();
                //    return;
                //}

                //var del = DB.PartyATMSaveAndTakes.FirstOrDefault(t => t.ID == PartyArticleId);
                //DB.PartyATMSaveAndTakes.Remove(del);
                //DB.SaveChanges();
                //BindGrid();
            }
        }
        #endregion
        #region 按钮事件
        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            //if (!CheckPower("PartyArticleDelete"))
            //{
            //    CheckPowerFailWithAlert();
            //    return;
            //}

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(grid);

            // 执行数据库操作
            //DB.PartyATMSaveAndTakes.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => DB.PartyATMSaveAndTakes.Remove(u));
            //DB.SaveChanges();

            // 重新绑定表格
            BindGrid();
        }

        protected void Dialog_Close(object sender, EventArgs e)
        {
            BindGrid();
        }

        #endregion

        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            DataSet ds = null;
            if (fileUpload.HasFile)
            {
                try
                {
                    ds = UploadFileHelp.ImportToDataSet(this.fileUpload, "Sheet1");
                }
                catch (Exception)
                {
                    Alert.Show("文件格式不正确，请检查！");
                    return;
                }
                if (ds != null && ds.Tables.Count > 0)
                {
                    ds.Tables[0].Columns.Add("数据状态");
                    ds.Tables[0].Columns.Add("BranchID");
                    ds.Tables[0].Columns.Add("Birthday");
                    ds.Tables[0].Columns.Add("JoinPartyDate");
                    ds.Tables[0].Columns.Add("BeRegularDate");
                }

                bool isSucceed = true;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (string.IsNullOrEmpty(dr["用户名"].ToString()) || string.IsNullOrEmpty(dr["姓名"].ToString())
                        || string.IsNullOrEmpty(dr["所属组织"].ToString())
                        || string.IsNullOrEmpty(dr["身份证号"].ToString()))
                    {
                        dr["数据状态"] = "<span style=\"color:red\">异常</span>";
                        isSucceed = false;
                    }
                    else
                    {

                        string branchID = PartyOrg.QueryBranchID(dr["所属组织"].ToString());
                        //string parentID = PartyOrg.QueryParentBranchIDBybranchname(dr["所属组织"].ToString());
                        if (!Regex.IsMatch(dr["用户名"].ToString(), @"^[a-zA-Z0-9_]+$"))
                        {
                            dr["数据状态"] = "<span style=\"color:red\">用户名异常</span>";
                            isSucceed = false;
                        }
                        else if (string.IsNullOrEmpty(branchID))
                        {
                            dr["数据状态"] = "<span style=\"color:red\">所属组织不存在</span>";
                            isSucceed = false;
                        }
                        else if (!PartyOrg.CheckLoginID(dr["用户名"].ToString()))
                        {
                            dr["数据状态"] = "<span style=\"color:red\">用户名已存在</span>";
                            isSucceed = false;
                        }
                        else if (!PartyOrg.CheckIdentityCard(dr["身份证号"].ToString()))
                        {
                            dr["数据状态"] = "<span style=\"color:red\">身份证号已存在</span>";
                            isSucceed = false;
                        }
                        else if (dr["出生年月"].ToString() == "")
                        {
                            dr["数据状态"] = "<span style=\"color:red\">出生年月不能为空</span>";
                            isSucceed = false;
                        }
                        else if (dr["入党时间"].ToString() == "")
                        {
                            dr["数据状态"] = "<span style=\"color:red\">入党时间不能为空</span>";
                            isSucceed = false;
                        }
                        else if (dr["转正时间"].ToString() == "")
                        {
                            dr["数据状态"] = "<span style=\"color:red\">转正时间不能为空</span>";
                            isSucceed = false;
                        }
                        else if (dr["手机号码"].ToString() == "")
                        {
                            dr["数据状态"] = "<span style=\"color:red\">手机号码不能为空</span>";
                            isSucceed = false;
                        }
                        dr["BranchID"] = branchID;
                        try
                        {
                            dr["Birthday"] = Convert.ToDateTime(dr["出生年月"]);
                        }
                        catch
                        {
                            dr["Birthday"] = null;
                        }
                        try
                        {
                            dr["JoinPartyDate"] = Convert.ToDateTime(dr["入党时间"]);
                        }
                        catch
                        {
                            dr["JoinPartyDate"] = null;
                        }
                        try
                        {
                            dr["BeRegularDate"] = Convert.ToDateTime(dr["转正时间"]);
                        }
                        catch
                        {
                            dr["BeRegularDate"] = null;
                        }
                    }
                    if (isSucceed)
                    {
                        dr["数据状态"] = "正常";
                    }
                }
                this.MemberSession = ds;
                this.grid.RecordCount = ds.Tables[0].Rows.Count;
                this.grid.PageSize = ConfigHelper.PageSize;
                this.grid.DataSource = ds;
                this.grid.DataBind();
            }
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            if (PartyOrgMember.SaveImport(((DataSet)this.MemberSession).Tables[0]))
            {
                //this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('数据导入成功');", true);
                Alert.Show("数据导入成功");

            }
            else
                Alert.Show("数据导入失败");
            //this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('数据导入失败');", true);
        }
    }
}